package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.pojo.system.Admin;
import com.qingcheng.service.system.AdminService;
import com.qingcheng.service.system.ResourceService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录认证的
 */
public class UserDetailServiceImpl implements UserDetailsService {

    @Reference
    private AdminService adminService;

    @Reference
    private ResourceService resourceService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        System.out.println("经过了UserDetailServiceImpl");

        //从数据库中查询管理员登录名称和密码
        Map map = new HashMap<>();
        map.put("loginName",s);
        map.put("status","1");
        List<Admin> adminList = adminService.findList(map);

        if(adminList.size()==0){
            return null;
        }

//        //实际项目中应该从数据库中提取用户的角色列表,感觉role数据库缺少res_key:ROLE_ADMIN这种
//        List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
//        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

        //构建权限列表
        List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
        List<String> resKetList = resourceService.findResKeyByLoginName(s);
        for(String resKey: resKetList){
            grantedAuthorities.add(new SimpleGrantedAuthority(resKey));
        }
        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

        return new User(s,adminList.get(0).getPassword(),grantedAuthorities);
    }
}
